package ext.tianma.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.workflow.NmWorkflowHelper;

import ext.com.iba.IBAUtil;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.iba.definition.StringDefinition;
import wt.iba.value.StringValue;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.part.WTPart;
import wt.query.KeywordExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.ClientTypedUtility;
import wt.type.TypeDefinitionForeignKey;
import wt.type.TypeDefinitionReference;
import wt.type.Typed;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.wip.WorkInProgressHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfRequester;
import wt.workflow.engine.WfRequesterActivity;

public class UpdateRawMaterial implements RemoteAccess{
	public static final String  partType  = "cn.tianma.RawMaterial";//原材料
	public static final String WhetherPartRecognize = "whetherPartRecognize";//IBA属性：是否已经样品承认
	public static final String discardState = "OBSOLESCENCE";//废弃状态
	public static final String PartRecognize = "partRecognize";//IBA属性：是否需要零件承认
	private static String wtHome = "";
	static {
		WTProperties wtproperties;
		try {
			wtproperties = WTProperties.getLocalProperties();
			wtHome = wtproperties.getProperty("wt.home", "");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		
		try {
			RemoteMethodServer rms = RemoteMethodServer.getDefault();
			rms.setUserName("wcadmin");
			rms.setPassword("tmadmin");
			rms.invoke("updateRawMaterial", UpdateRawMaterial.class.getName(),null,null,null);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 批量刷原材料是否已经样品承认属性
	 * @throws IOException 
	 */
	public static void updateRawMaterial() throws IOException{
		String filepath = wtHome+ File.separator + "temp"+ File.separator + "modifyLdapIBA.log";
		File myFilePath = new File(filepath);
	      if(!myFilePath.exists()){
	        myFilePath.createNewFile();
	      }
		FileWriter fileWriter = new FileWriter(myFilePath);
		String filepathFail = wtHome+ File.separator + "temp"+ File.separator + "modifyLdapFailIBA.log";
		File myFilePathFail = new File(filepathFail);
	      if(!myFilePathFail.exists()){
	    	  myFilePathFail.createNewFile();
	      }
		FileWriter fileWriterFail = new FileWriter(myFilePathFail);
		WfProcess process = null;
		long start = System.currentTimeMillis();
		try {
			List<WTPart> rawMaterials = getRawMaterial();
			fileWriter.write("--------rawMaterials长度---------"+rawMaterials.size()+"\n");
			for(int i=0; i<rawMaterials.size(); i++) {
				WTPart part = rawMaterials.get(i);
				Persistable p = (Persistable) part;
	            NmOid nmoid = NmOid.newNmOid(PersistenceHelper.getObjectIdentifier(p));
	            QueryResult qr = NmWorkflowHelper.service.getRoutingHistoryData(nmoid);
	            while (qr.hasMoreElements()){
	                process = (WfProcess) qr.nextElement();
	                String name = process.getName();//获得流程name
	                if(name.contains("样品承认及批准流程")) {
	                	if (isCheckOut(part)) {
	    					fileWriterFail.write("[检出状态]"+part.getNumber()+"\n");
	    					break;
	    				}
	                	//判断wfRequester,如果wfRequester不为空,且类型为WfRequesterActivity那么process就是子流程
		                WfRequester wfRequester = process.getRequester();
	                	if (wfRequester != null && (wfRequester instanceof WfRequesterActivity)) {
		                	ext.com.iba.IBAUtil.forceSetIBAValue(part,WhetherPartRecognize,"是");//设置是否已经样品承认属性为“是”
		                	fileWriter.write("--------part属性: 是---------part编号："+part.getNumber()+"\n");
		                	String whetherPartRecognize = IBAUtil.getIBAValue(part,WhetherPartRecognize)==null ? "": ((String) IBAUtil.getIBAValue(part,WhetherPartRecognize));
		                	fileWriter.write("----------whetherPartRecognize属性 是="+whetherPartRecognize+"\n");
		                	break;
		                }else {
		                	ext.com.iba.IBAUtil.forceSetIBAValue(part,WhetherPartRecognize,"正在审核");//设置是否已经样品承认属性为“正在审核”
		                	fileWriter.write("--------part属性: 正在审核---------part编号"+part.getNumber()+"\n");
		                	String whetherPartRecognize = IBAUtil.getIBAValue(part,WhetherPartRecognize)==null ? "": ((String) IBAUtil.getIBAValue(part,WhetherPartRecognize));
		                	fileWriter.write("----------whetherPartRecognize属性 正在审核="+whetherPartRecognize+"\n");
		                }
	                }
	            }
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		fileWriter.write("****** 执行更新是否已经样品承认属性接口共用时间:"+(end-start)/1000+"秒\n");
		fileWriter.close();
		fileWriterFail.close();
	}
	/**
	 * 获取所有非废弃状态需要样品承认的原材料part
	 * 
	 * @return
	 * @throws WTException
	 */
	public static List<WTPart> getRawMaterial() throws WTException{
		List<WTPart> list = new ArrayList<WTPart>();
		QuerySpec qs = new QuerySpec();
	    int docIndex = qs.appendClassList(WTPart.class, true);
	    int defIndex = qs.appendClassList(StringDefinition.class, false);
	    int valueIndex = qs.appendClassList(StringValue.class, false);
	    View view = ViewHelper.service.getView("Design");
		try {
			//增加过滤条件：iba属性存在值
			TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(partType);
			SearchCondition scOther = new SearchCondition(WTPart.class,
					Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
							+ TypeDefinitionForeignKey.BRANCH_ID,
					SearchCondition.EQUAL, clientType.getKey().getBranchId());
			qs.appendWhere(scOther,new int[]{0});
			qs.appendAnd();
			SearchCondition scState = new SearchCondition(WTPart.class,WTPart.LIFE_CYCLE_STATE,SearchCondition.NOT_EQUAL,discardState);
			qs.appendWhere(scState,new int[]{0});
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(WTPart.class, "view.key.id",
					SearchCondition.EQUAL, view.getPersistInfo().getObjectIdentifier().getId()));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.ida2a2"), SearchCondition.EQUAL,
		    	    new KeywordExpression("A2.ida3a4")));
	    	qs.appendAnd();
    	    qs.appendWhere(new SearchCondition(new KeywordExpression("A2.ida3a6"), SearchCondition.EQUAL,
    	    		new KeywordExpression("A1.ida2a2")));
    	    qs.appendAnd();
    	    qs.appendWhere(new SearchCondition(new KeywordExpression("A1.name"), SearchCondition.EQUAL,
        	        new KeywordExpression("'"+PartRecognize+"'")));
        	qs.appendAnd();
        	qs.appendWhere(new SearchCondition(new KeywordExpression("A2.value2"), SearchCondition.EQUAL,
        	        new KeywordExpression("'是'")));
			QueryResult qr = PersistenceHelper.manager.find(qs);
			while(qr.hasMoreElements()){
				Object obj[] = (Object[])qr.nextElement();
				if(obj[0] instanceof WTPart){
					WTPart part = (WTPart) obj[0];
					list.add(part);
				}  
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 判断该零件是否已经出库
	 * 
	 * @param part
	 *            零件对象
	 * @return true:出库<br>
	 *         false:未出库
	 */
	public static boolean isCheckOut(WTPart part) {
		boolean isCheckOut = false;
		if (part != null) {
			try {
				isCheckOut = WorkInProgressHelper.isCheckedOut(part);/* 获取零件的出库状态 */
			} catch (WTException e) {
				e.printStackTrace();
			}
		} // end if

		return isCheckOut;
	}
}
